package com.webserver.core;

import com.webserver.controller.UserController;
import com.webserver.core.ClientHandler;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static File rootDir,staticDir;

    static {
        try {
            rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        staticDir = new File(rootDir,"static");
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequestURI();

        //根据请求路径判断是否为处理某个业务
        if("/myweb/reg".equals(path)){
            UserController controller = new UserController();
            controller.reg(request,response);//创建UserController对象,执行注册
        }else if("/myweb/login".equals(path)){
            UserController controller = new UserController();
            controller.login(request,response);//执行登入
        }else {
            File file = new File(staticDir,path);
            System.out.println("资源是否存在："+file.exists());
            if(!file.isFile()){
                file = new File(staticDir,"root/404.html");
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
            }
            response.setContentFile(file);
        }



    }

}
